﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DiscoveryLogic.Analytics.BusinessLogic.Entities;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.UI.Common.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Events;

namespace DiscoveryLogic.Analytics.Modules.Entities
{
    public class OrgListPresenter
    {
        private OrgListView _View;
		/// <summary></summary>
		public OrgListView View
		{
			get
			{
				return this._View;
			}
			set
			{
				this._View = value;
				if(this._View !=null)
				{
					this._View.OrgSelected += new OrgListView.OnOrgSelected(SelectOrg);
					this._View.Orgs = this.ReadOrgList();
				}
			}
		}

		private readonly IEventAggregator _EventAggregator;
        private SubscriptionToken _SubscriptionToken;

        public OrgListPresenter(IEventAggregator eventAggregator)
		{
			this._EventAggregator = eventAggregator;
		}

        public void SelectOrg(ExternalOrgDO org)
        {
            if (org != null)
            {
                this._EventAggregator.GetEvent<OrganizationSelectedEvent>().Publish(org);
            }
        }

        public void RegisterOrgSelectionChangedEventHandler(ExternalOrgDO org)
        {
            OrganizationSelectedEvent orgSelectedEvent =
                    _EventAggregator.GetEvent<OrganizationSelectedEvent>();
            if (this._SubscriptionToken != null)
            {
                orgSelectedEvent.Unsubscribe(_SubscriptionToken);
            }
            this._SubscriptionToken = orgSelectedEvent.Subscribe(
                OrgSelectedHandler,
                ThreadOption.UIThread,
                false);
        }

        private void OrgSelectedHandler(ExternalOrgDO org)
        {
            this._View.SelectOrg(org);
        }

        private List<ExternalOrgDO> ReadOrgList()
        {
            return EntityManager.GeneratOrgsForTest();
        }
    }
}
